from socket import *
import os,sys
import multiprocessing as mp

def recv_msg(s):
	while True:
		data, addr = s.recvfrom(2048)
		if data.decode() == 'EXIT':
			os._exit(0)
		print(data.decode() + '\n发言', end='')

def send_msg(s, name):
	while True:
		try:
			text = input('发言:')
		except: KeyboardInterrupt:
			text = 'quit'
		if text == 'quit':
			msg = 'Q' + name
			s.sendto(msg.encode(),ADDR)
			sys.exit('退出聊天室')
		msg = 'C %s %s' % (name, text)
		s.sendto(msg.encode(),ADDR)
		
def main():
	if len(sys.argv) < 3:
		print('argv is error!')
		return
	HOST = sys.argv[1]
	PORT = int(sys.argv[2])
	ADDR = (HOST,PORT)

	s = socket(AF_INET,SOCK_DGRAM)
	
	while True:
		name = input('input name please >>')
		msg = 'L ' + name
		# 给服务器发送
		s.sendto(msg.encode(), ADDR)
		# 接受反馈
		data,addr = s.recvfrom(1024)
		if data.decode() == 'OK':
			print('You have enter the chat room')
			break
		else:
			print(data.decode())
		p = mp.Process(target=send_msg, args=(s, name))
		p.start()
		recv_msg(s)
		# p.start()

if __name__ == '__main__':
	main()
